<template>
  <el-dialog title="收货地址" :visible="visible" :show-close="false" @close="$emit('update:visible', false)">
    <el-form ref="userForm" :model="form" :rules="validateRules()" :label-width="formLabelWidth">
      <el-form-item label="账号" prop="username">
        <el-input v-model="form.username" autocomplete="off" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="form.sex">
          <el-radio label="先生"></el-radio>
          <el-radio label="女士"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="生日日期" prop="date1">
        <el-date-picker type="date" placeholder="选择日期" v-model="form.date1" style="width: 100%"></el-date-picker>
      </el-form-item>
      <el-form-item label="头像">
        <!-- 头像上传 -->
        <el-upload action="/api/upfile" :auto-upload="false" :show-file-list="false" :on-change="changeHandle">
          <el-button size="small" type="primary">上传头像</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif文件，且不超过500kb</div>
        </el-upload>
        <el-image style="width: 100px; height: 100px" :src="form.avatar" fit="fill"></el-image>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="$emit('update:visible', false)">取 消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">{{ form.id ? '修改用户' : '添加用户' }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
// import siteConfig from '@/config/site'
import { errorMsg, successMsg } from '@/utils/msg'
import { uploadAvatar, addUserApi, editUserApi } from '@/api/userApi'

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      // host: siteConfig.requestHost,
      form: {
        username: '',
        password: '',
        sex: '女士',
        date1: '2022-09-13',
        avatar: ''
      },
      formLabelWidth: '120px'
    }
  },
  methods: {
    async changeHandle(file) {
      if (!file) return
      // 判断当前的上传文件是否为图片
      if (!/\.(jpe?g|png|gif)/i.test(file.name)) {
        errorMsg('图片格式不正确')
        return
      }
      // 图片大小限制
      // console.log(file.size/1024);

      // 把File对象传到服务器
      const formData = new FormData()
      formData.append('file', file.raw)
      // 使用 ajax提交
      let ret = await uploadAvatar(formData)
      if (ret.code === 0) {
        this.form.avatar = ret.data.path
      }
    },
    // 点击添加用户后
    doSubmit() {
      this.loading = true
      this.$refs['userForm'].validate(async valid => {
        // 前端表单验证通过
        if (valid) {
          // 针对于图片是否有上传做一次验证
          if (this.form.avatar == '') {
            errorMsg('头像必须要上传一下')
            return false
          }
          let ret
          // 进行网络请求
          if (!this.form.id) {
            // 添加
            ret = await addUserApi(this.form)
          } else {
            // 修改
            ret = await editUserApi(this.form, this.form.id)
          }
          if (ret.code === 0) {
            successMsg('保存用户成功', () => {
              // 添加用户数据到远程，清空表单中的数据
              this.$refs['userForm'].resetFields()
              this.form.avatar = ''
              this.loading = false
              let page = this.$route.query.page || 1
              // 获取父组件对象
              this.$parent.loadData(page).then(() => {
                // 让弹出层关闭
                this.$emit('update:visible', false)
              })
            })
          } else {
            errorMsg('保存用户异常', () => {
              this.loading = false
            })
          }
        } else {
          errorMsg('表单验证不通过，请认真检查')
          return false
        }
      })
    },
    validateRules() {
      return {
        username: [
          { required: true, message: '账号不能为空' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符' },
          { validator: this.checkUsername }
        ],
        password: [{ required: true, message: '密码不能为空' }]
      }
    },
    checkUsername(rule, value, callback) {
      // callback(new Error('账号已经存在'))
      callback()
    }
  }
}
</script>

<style lang="scss" scoped></style>
